import { defineStore } from 'pinia';
import { ref } from 'vue';
import type { UserInfo, Coupon } from '../types/http';
import Storage from '../utils/storage';
import api from '../api';

const STORAGE_KEY_USER = 'user_info';
const STORAGE_KEY_TOKEN = 'user_token';

export const useUserStore = defineStore('user', () => {
  // 状态
  const userInfo = ref<UserInfo | null>(Storage.get(STORAGE_KEY_USER));
  const token = ref<string | null>(Storage.get(STORAGE_KEY_TOKEN));
  const isLogin = ref<boolean>(!!token.value);
  const scoreBalance = ref<number>(0);
  const exchangeHistory = ref<Array<{date: string; points: number}>>([]);

  // 设置用户信息
  const setUserInfo = (info: UserInfo | null) => {
    userInfo.value = info;
    if (info) {
      Storage.set(STORAGE_KEY_USER, info);
    } else {
      Storage.remove(STORAGE_KEY_USER);
    }
  };

  // 设置token
  const setToken = (newToken: string | null) => {
    token.value = newToken;
    isLogin.value = !!newToken;
    if (newToken) {
      Storage.set(STORAGE_KEY_TOKEN, newToken);
    } else {
      Storage.remove(STORAGE_KEY_TOKEN);
    }
  };

  // 登录
  const login = (loginInfo: { token: string; userInfo: UserInfo }) => {
    setToken(loginInfo.token);
    setUserInfo(loginInfo.userInfo);
  };

  // 登出
  const logout = () => {
    setToken(null);
    setUserInfo(null);
  };

  // 更新用户信息
  const updateUserInfo = (info: Partial<UserInfo>) => {
    if (userInfo.value) {
      setUserInfo({
        ...userInfo.value,
        ...info,
      });
    }
  };

  // 获取分销数据
  const getDistributionData = async () => {
    try {
      const res = await api.user.getDistributionData()
      return {
        commission: res.commission,
        team: res.team
      }
    } catch (error) {
      console.error('获取分销数据失败:', error)
      throw error
    }
  }

  // 生成推广二维码
  const generateQRCode = async () => {
    try {
      const res = await api.user.generateQRCode()
      return res.qrcode
    } catch (error) {
      console.error('二维码生成失败:', error)
      throw error
    }
  }

  // 优惠券相关状态和方法
  const coupons = ref<Coupon[]>([])
  const mergedIds = ref<string[]>([])

  const fetchCoupons = async () => {
    try {
      const res = await api.user.getCoupons()
      coupons.value = res.list
      return res
    } catch (error) {
      console.error('获取优惠券失败:', error)
      throw error
    }
  }

  const acquireCoupon = async (id: string) => {
    try {
      await api.user.acquireCoupon(id)
      coupons.value = coupons.value.map(c => 
        c.id === id ? {...c, received: (c.received || 0) + 1} : c
      )
    } catch (error) {
      if (error.code === 4001) {
        throw new Error('库存不足')
      }
      throw new Error('领取失败: ' + error.message)
    }
  }

  const updateCoupons = (newCoupon: Coupon) => {
    coupons.value = coupons.value.filter(c => !mergedIds.value.includes(c.id))
    coupons.value.unshift(newCoupon)
  }

  return {
    userInfo,
    token,
    isLogin,
    scoreBalance,
    exchangeHistory,
    coupons,
    mergedIds,
    setUserInfo,
    setToken,
    login,
    logout,
    updateUserInfo,
    getDistributionData,
    generateQRCode,
    fetchCoupons,
    acquireCoupon,
    updateCoupons
  };
});